package com.gambi.example.client.gwtui.widgets;

import com.gambi.example.client.gwtui.services.CheckBoxService;
import com.gambi.example.client.gwtui.services.CheckBoxServiceAsync;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.Dictionary;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.RootPanel;

public class CheckBoxWidget extends Composite {
	private final CheckBoxServiceAsync checkBoxService = GWT
			.create(CheckBoxService.class);
	final Dictionary dictionary;

	public CheckBoxWidget(String id, Dictionary d) {
		this.dictionary = d;
		// checkBoxService).setServiceEntryPoint(dictionary.get("completeID"));
		((ServiceDefTarget) checkBoxService).setServiceEntryPoint(dictionary
				.get("eventLink"));
		CheckBox checkBox = new CheckBox();
		checkBox.addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent event) {
				sendValue(((CheckBox) event.getSource()).getValue());

			}
		});

		initWidget(checkBox);
	}

	void sendValue(Boolean value) {
		// Some smart way to embed parameters in URL or reference them in the
		// post body

		checkBoxService.onChange(value, new AsyncCallback<String>() {
			public void onFailure(Throwable caught) {
				GWT.log("OnFailure " + caught.getMessage());
			}

			public void onSuccess(String result) {
				GWT.log("OnSuccess " + result);
				String div = dictionary.get("div");
				if (div.length() > 0) {
					Element e = RootPanel.get(div).getElement();
					e.setInnerHTML(result);
				}

			}
		});
	}
}
